package com.boyou.cameraxdemo;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.camera.core.Camera;
import androidx.camera.core.CameraSelector;
import androidx.camera.core.ImageAnalysis;
import androidx.camera.core.ImageCapture;
import androidx.camera.core.ImageCaptureException;
import androidx.camera.core.ImageProxy;
import androidx.camera.core.Preview;
import androidx.camera.core.impl.ImageCaptureConfig;
import androidx.camera.lifecycle.ProcessCameraProvider;
import androidx.camera.view.PreviewView;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.google.common.util.concurrent.ListenableFuture;

import java.io.File;
import java.nio.ByteBuffer;
import java.text.SimpleDateFormat;
import java.util.Locale;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 参考链接：
 * https://blog.csdn.net/cunchi4221/article/details/107477938 相机
 * https://www.jianshu.com/p/6ddc521c048d 相机
 * https://zhuanlan.zhihu.com/p/161812469 相机
 */
public class MainActivity extends AppCompatActivity {

    private int REQUEST_CODE_PERMISSIONS = 101;
    private final String[] REQUIRED_PERMISSIONS = new String[]{"android.permission.CAMERA", "android.permission.WRITE_EXTERNAL_STORAGE"};

    private static final String TAG = "CameraXActivity";
    private static final String FILENAME_FORMATE = "yyyy-MM-DD-HH-mm-ss";
    private ExecutorService cameraExecutor;
    private Preview preview;
    Camera camera;
    private PreviewView viewFinder;
    ProcessCameraProvider cameraProvider;
    Button imageButton;
    ImageCaptureConfig imageCaptureConfig;
    private ImageCapture imageCapture;
    ImageAnalysis myAnalyzer;
    ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();
    }

    private void initView() {
        viewFinder = findViewById(R.id.viewFinder); // 预览窗口
        imageButton = findViewById(R.id.camera_capture_button); // 拍照按钮
        if (allPermissionsGranted()) {
            startCamera(); // 开启相机
        } else {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, 10);
        }
        cameraExecutor = Executors.newSingleThreadExecutor();
        // 点击事件
        imageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                takephoto();
            }
        });
    }

    private void startCamera() {
        // 创建一个相机的管理器，相当于一个主管道。
        ListenableFuture<ProcessCameraProvider> cameraProviderFuture = ProcessCameraProvider.getInstance(this);
        cameraProviderFuture.addListener(new Runnable() {
            @Override
            public void run() {
                try {
                    //1 图像预览接口
                    preview = new Preview.Builder().build();
                    //2 图像分析接口
                    myAnalyzer = new ImageAnalysis.Builder().build();
                    myAnalyzer.setAnalyzer(cameraExecutor, new LuminosityAnalyzer());
                    //3 拍照 接口
                    imageCapture = new ImageCapture.Builder().build();
                    //4 把我们需要的这三个接口安装到相机管理器的主线路上，实现截取数据的目的
                    CameraSelector cameraSelector = new CameraSelector.Builder().requireLensFacing(CameraSelector.LENS_FACING_BACK).build();
                    cameraProvider = cameraProviderFuture.get();
                    cameraProvider.unbindAll();
                    camera = cameraProvider.bindToLifecycle(MainActivity.this, cameraSelector, preview, imageCapture, myAnalyzer);
                    //5 把相机的信息还得告诉预览窗口以做好准备显示数据
                    preview.setSurfaceProvider(viewFinder.createSurfaceProvider(camera.getCameraInfo()));
                } catch (ExecutionException e) {
                    Log.e(TAG, "run: binding lifecycle failed");
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, ContextCompat.getMainExecutor(this));
    }

    private void takephoto() {
        //1 设置要保存的路径和文件名字
        File photoFile = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), "image-" + new SimpleDateFormat(FILENAME_FORMATE, Locale.CHINA).format(System.currentTimeMillis()) + ".jpg");
        //2 定义 拍摄imageCapture实例
        ImageCapture.OutputFileOptions outputFileOptions =  new ImageCapture.OutputFileOptions.Builder(photoFile).build();
        imageCapture.takePicture(outputFileOptions, cameraExecutor, new ImageCapture.OnImageSavedCallback() {
            @Override
            public void onImageSaved(@NonNull ImageCapture.OutputFileResults outputFileResults) {
                //保存成功
            }

            @Override
            public void onError(@NonNull ImageCaptureException exception) {
                //"保存失败"+
            }
        });
    }

    class LuminosityAnalyzer implements ImageAnalysis.Analyzer {

        @Override
        public void analyze(@NonNull ImageProxy image) {
            ByteBuffer buffer = image.getPlanes()[0].getBuffer();
            byte[] b = new byte[buffer.remaining()];
            buffer.get(b);
            // 按你的需要处理图片吧

            image.close();
        }
    }

    private boolean allPermissionsGranted(){

        for(String permission : REQUIRED_PERMISSIONS){
            if(ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED){
                return false;
            }
        }
        return true;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

        if(requestCode == REQUEST_CODE_PERMISSIONS){
            if(allPermissionsGranted()){
                startCamera();
            } else{
                Toast.makeText(this, "Permissions not granted by the user.", Toast.LENGTH_SHORT).show();
                finish();
            }
        }
    }


//    @Override
//    public void onImageSaved(@NonNull ImageCapture.OutputFileResults outputFileResults) {
//        // 先获取路径
//        Uri uri= Uri.fromFile(photoFile);
//        if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
//            // 把任务发送给消息队列
//            imageView.post(new Runnable() {
//                @Override
//                public void run() {
//                    // 用glide加载这个图片
//                    Glide.with(imageView).load(uri).into(imageView);
//                }
//            });
//
//        }
//        showToast("保存完成");
//        // 让相册扫描这个图片 未实现
////                MediaScannerConnection.scanFile(getBaseContext(),Arrays.asList(uri.toString()));
//    }
}
